package com.mao.config;

import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/*
user：mao
data：2021/6/9
note：
*/

@Configuration
//Spring里面有一个WebMvcAutoConfigurationAdapter类继承了WebMvcConfigurer进行自动配置
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //可以将请求路径和对应模板进行匹配。
        //success文件必须放在templates里面，并且需要添加thymeleaf的POM依赖。
        registry.addViewController("/msb").setViewName("success");
        //感觉MVC里面可以走两条路径，或者是走Controller 或者或者直接走试图解析器。
        registry.addViewController("/login").setViewName("login");
    }


    //此bean覆盖掉了自动配置里面解析器。
    @Bean
    public LocaleResolver localeResolver(){
        return new NativeLocaleResolver();
    }

    protected static class NativeLocaleResolver implements LocaleResolver{

        @Override
        public Locale resolveLocale(HttpServletRequest request) {
            String language = request.getParameter("lan");
            Locale locale = Locale.getDefault();
            if(!StringUtils.isEmpty(language)){
                String[] split = language.split("_");
                locale = new Locale(split[0],split[1]);
            }
            return locale;
        }
        @Override
        public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
        }
    }
}



